package tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@WebServlet("/changeOrderServlet")
public class changeOrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String key = request.getParameter("key");
        String order_id = request.getParameter("order_id");
        try {
            Connection con = null;
            Statement stmt = null;
            Class.forName("org.h2.Driver");
            /*url后面加的?useUnicode=true&characterEncoding=gbk，是为了处理向数据库中添加数据时出现乱码的问题。*/
            String url = "jdbc:h2:~/test1";
            //System.out.println("到达");
            con = DriverManager.getConnection(url, "root", "root");
            //System.out.println("到达2");
            HttpSession session = request.getSession();
            stmt=con.createStatement();
            //当key为1的时候修改配送状态
            if (key.equals("1")) {
                //UPDATE "ORDER" SET STATE='已支付' WHERE ORDER_ID='33001'
                String sql= "UPDATE \"ORDER\" SET STATE='配送中' WHERE ORDER_ID='"+order_id+"'";
                stmt.executeUpdate(sql);
                System.out.println("删除成功");
            }
            //否则修改
            else {
                //new String(fi.getString().getBytes("ISO-8859-1"),"UTF-8")
                String address = new String(request.getParameter("address").getBytes("ISO-8859-1"),"UTF-8");
                String sql="UPDATE \"ORDER\" SET ADDRESS='"+address+"' WHERE ORDER_ID='"+order_id+"'";
                stmt.executeUpdate(sql);
                System.out.println("删除成功");
            }
            stmt.close();
            con.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        //跳转
        if (key.equals("1")) {
            response.sendRedirect("http://localhost:8080/order_deliveryServlet");

        }
        else {
            response.sendRedirect("http://localhost:8080/order_manageServlet");
        }
        return;
    }
}
